<script lang="ts"  setup>
import { onMounted, onUnmounted, ref, reactive } from 'vue';
import {
  Meta2d,
  register,
  registerAnchors,
  registerCanvasDraw,
} from '@meta2d/core';
import { flowPens, flowAnchors } from '@meta2d/flow-diagram';
import {
  activityDiagram,
  activityDiagramByCtx,
} from '@meta2d/activity-diagram';
import { classPens } from '@meta2d/class-diagram';
import { sequencePens, sequencePensbyCtx } from '@meta2d/sequence-diagram';
import { register as registerEcharts } from '@meta2d/chart-diagram';
import { registerHighcharts } from '@meta2d/chart-diagram';
import { registerLightningChart } from '@meta2d/chart-diagram';
import { formPens, formPath2DPens } from '@meta2d/form-diagram';
import { chartsPens } from '@meta2d/le5le-charts';
import { ftaPens, ftaPensbyCtx, ftaAnchors } from '@meta2d/fta-diagram';
import { useRoute } from 'vue-router';

const route = useRoute();

// 接地线开关
const gwire001 = reactive({
  id: 'gwire001',
  status: 'off',
});

// 电气开关
const switch003 = reactive({
  id: 'switch003',
  status: 'off',
});

let meta2d:any = null;

onMounted(async () => {
  const options = {
    background: 'transparent',
    color: '#000',
    width: undefined,
    height: undefined
  }
  meta2d = new Meta2d('meta2d',options);

  //注册基本图形库
  registerBasicDiagram();
  meta2d.on('opened',opened);
  open();

  //注册企业图形库
  setTimeout(async()=>{
    (globalThis as any).userId = meta2d.store.data.userId;
    (globalThis as any).registerIot((globalThis as any).userId,'/js/2d-components.js');
    if ((globalThis as any).meta2dTools && (globalThis as any).registerToolsNew) {
      (globalThis as any).registerToolsNew();
    }
  },1000);

  handleCrontabTask();
});

const opened = () => {
  meta2d.fitView(true, 0); //充满屏幕
}

const open = ()=>{
  let url = '/json/2d.json';

  if (route.query.id) {
    url = `/json/${route.query.id}.json`;
  } 

  _fetch(url, function (text:any) {
    var data = JSON.parse(text);
    data.locked = 1;
    data.rule = false;
    (globalThis as any).userId = data.userId;
    meta2d.open(data);
  });
}

function _fetch(url:any, cb:any) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.send();
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
      cb && cb(xhr.responseText);
    }
  };
}

function handleCrontabTask():void {
  if (route.query.id !== '2d-Debug') {
    return;
  }
  
  setTimeout(() => {
    handleGWireTask();
    handleCrontabTask();
  }, 1500);

  setTimeout(() => {
    handleSwitchTask();
  }, Math.random() * 1500);
};

const handleGWireTask = () => {
  if (gwire001.status == 'on') {
    handleGWireTurn(gwire001.id, 'off', gwire001);
    handleElecLineColor('mainLine001', 'red');
  } else {
    handleGWireTurn(gwire001.id, 'on', gwire001);
    handleLineTask();
  }
};

const handleSwitchTask = () => {
  if (switch003.status == 'on') {
    handleSwitchTurn(switch003.id, 'off', switch003);
  } else {
    handleSwitchTurn(switch003.id, 'on', switch003);
  }
};

const handleLineTask = () => {
  const colors = ['green', 'green', 'orange', 'green', 'blue', 'skyblue', 'green', 'purple', 'green', 'green']
  handleElecLineColor('mainLine001', colors[Math.floor(Math.random() * 10)]);
}

// 对接地线GWire开关进行开关控制
const handleGWireTurn = (id = 'gwire001', status = 'on', obj = {}) => {
  if (status == 'off') {
    meta2d.setValue({
      id,
      iconFamily: "sgcc",
      icon: "",
      color: "red",
    });
    Reflect.set(obj, 'status', status);
  } else if (status == 'on'){
    meta2d.setValue({
      id,
      iconFamily: "sgcc",
      icon: "",
      color: "green",
    });
    Reflect.set(obj, 'status', status);
  }
}

// 对电路开关进行开关控制
const handleSwitchTurn = (id = 'switch001', status = 'on', obj = {}) => {
  if (status == 'off') {
    meta2d.setValue({
      id,
      "iconFamily": "ltdx",
		  "icon": "",
      color: "red",
    });
    Reflect.set(obj, 'status', status);
  } else if (status == 'on'){
    meta2d.setValue({
      id,
      "iconFamily": "ltdx",
		  "icon": "",
      color: "green",
    });
    Reflect.set(obj, 'status', status);
  }
}

// 对电力电线颜色控制
const handleElecLineColor = (id = 'mainLine001', color = 'green') => {
  meta2d.setValue({
    id,
    background: color,
  });
}

//参考文档:https://doc.le5le.com/document/119754049
function registerBasicDiagram() {
  register(flowPens());
  registerAnchors(flowAnchors());
  register(activityDiagram());
  registerCanvasDraw(activityDiagramByCtx());
  register(classPens());
  register(sequencePens());
  registerCanvasDraw(sequencePensbyCtx());
  registerEcharts();
  registerHighcharts();
  registerLightningChart();
  register(formPath2DPens());
  registerCanvasDraw(formPens());
  registerCanvasDraw(chartsPens());
  register(ftaPens());
  registerCanvasDraw(ftaPensbyCtx());
  registerAnchors(ftaAnchors());
}


onUnmounted(() => {
  meta2d?.off('opened',opened);
  meta2d?.destroy();
});
</script>

<template>
  <div class="content">
    <div id="meta2d"></div>
  </div>
</template>

<style scoped>
#meta2d {
  position: absolute !important;
  width: 100%;
  height: 100%;
  touch-action: none;
  overflow: hidden;
}
</style>
